import cgi
import logging
import os
from datetime import date
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.ext.webapp import template

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings';
from django.conf import settings
from ezhangbendef import *
from cookies import Cookies
from i18n_own import *

from trans import *
from statistics import *
from income import *

# Force Django to reload settings
settings._import_settings()

class MainPage(I18NHandler):

    def get(self):
        choose_language = self.request.get('language')
        self.reset_language()
        logging.info("current language:%s"%translation.get_language());
        url_linktext = ''
        url = ''
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            cur_user = users.User()
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)

        tr = Transcation
        t = tr.all()
        query = t.filter('owner = ',users.get_current_user())
        query = t.order('-date')

        total = 0.0
        try:
            for q in query:
                if (q.amountnum == None):
                    break;
                n = str(q.amountnum)
                num = float(n)
                if (q.is_pay == False):
                    total += num
                else:
                    total -= num
        except ValueError, err:
            self.response.out.write("<html><body><h2>Server Error<h2><pre>%s</pre></body></html>"%err)
            self.response.set_status(500)
            return

        totalstr= str("%.2f"%total)
        if users.get_current_user():
            template_map = {
                'expense_catelog_table':expense_catelog_dic,
                'expense_through_table':expense_through_dic,
                'expense_to_whom_table':expense_to_whom_dic,
                'incoming_dic': incoming_dic,
                'usernickname':cur_user.nickname(),
                'querys': query,
                'logout_url':url,
                'logout_url_text':url_linktext,
                'TODAY' : date.today(),
                'TOTALMONEY' : totalstr,
                }
#            template_file_name = 'index-simple.html'
            template_file_name = 'index-js.html'
        else:
            template_file_name = 'login_index.html'
            template_map = {
                'login_url': url,
                }

        logging.info(os.path.dirname(__file__) +  template_file_name);
        path = os.path.join(os.path.dirname(__file__), template_file_name)
        self.response.out.write(template.render(path, template_map))
#        self.render_template(template_file_name, template_map);


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/addincome', AddIncome),
                                      ('/addexpense', AddExpense),
                                      ('/statistics', Statistics),
                                      ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()


